import type { Configuration as DevServerConfiguration } from 'webpack-dev-server';
import * as path from 'path';
import * as fs from 'fs';
import proxy from './proxy';

const host = process.env.HOST || '0.0.0.0';
const port = parseInt(process.env.PORT!, 10) || 3000;
const sockHost = process.env.WDS_SOCKET_HOST;
const sockPath = process.env.WDS_SOCKET_PATH; // default: '/ws'
const sockPort = process.env.WDS_SOCKET_PORT;

// console.log(process.env, 'process.env')

const devServer: DevServerConfiguration = {
    allowedHosts: 'all', //跳过 host 检查。并不推荐这样做
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': '*',
        'Access-Control-Allow-Headers': '*',
    },
    compress: true,
    static: {
        directory: path.join(__dirname, '../public'),
    },
    client: {
        overlay: false,
        reconnect: 3,
        webSocketURL: {
            hostname: sockHost,
            pathname: sockPath,
            port: sockPort,
        },
    },
    https: false,
    host,
    hot: false,
    liveReload: true,
    open: true,
    port,
    historyApiFallback: true,
    // `proxy` is run between `before` and `after` `webpack-dev-server` hooks
    proxy,
    watchFiles: ['src/**/*', 'public/**/*'],
    setupMiddlewares(middlewares, devServer) {
        // 自定义http-proxy-middleware
        const proxySetup = path.join(__dirname, '../src/setupProxy.js');
        if (fs.existsSync(proxySetup)) {
            require(proxySetup)(devServer.app);
        }
        return middlewares;
    },
};

export default devServer;
